package com.base.library.utils

import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import java.lang.ref.WeakReference

object ActivityUtils {
    private val mActivitys = mutableListOf<Activity>()
    private var mCurActivity: WeakReference<Activity?>? = null
    fun init(application: Application) {
        application.registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                mActivitys.add(activity)
            }

            override fun onActivityStarted(activity: Activity) {
            }

            override fun onActivityResumed(activity: Activity) {
                mCurActivity = WeakReference(activity)
            }

            override fun onActivityPaused(activity: Activity) {
            }

            override fun onActivityStopped(activity: Activity) {
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
                mActivitys.remove(activity)
            }

        })
    }

    fun containsActivity(cl: Class<out Activity>): Boolean {
        for (activity in mActivitys) {
            if (activity.javaClass == cl) {
                return true
            }
        }
        return false
    }

    fun getTopActivity(): Activity? {
        return mCurActivity?.get()
    }

    fun closeAllActivity() {
        for (activity in mActivitys) {
            if (activity.isDestroyed || activity.isFinishing) {
                continue
            }
            activity.finish()
        }
    }
}